import { STATIC_URL } from "@/configs/yz";
import type { RoomLogMessageData } from "../types/MessageData";
import { useRoomState } from "@/hooks/useRoomState";

export const roomLogHandler = (payload: RoomLogMessageData["payload"]) => {
	const roomState = useRoomState();
	if (roomState.room.value) roomState.room.value.logs.push(payload);
	const speakingIndex = roomState.speaking.findIndex((v) => v.userId === payload.userId);
	if (speakingIndex != -1) {
		clearTimeout(roomState.speaking[speakingIndex].timer);
		roomState.speaking.splice(speakingIndex, 1);
	}
	const playerIndex = roomState.room.value?.players.findIndex((v) => v.user.userId === payload.userId);
	if (playerIndex != -1) {
		roomState.speaking.push({
			userId: payload.userId,
			message: payload.log,
			timer: setTimeout(() => {
				const index = roomState.speaking.findIndex((v) => v.userId === payload.userId);
				if (index != -1) roomState.speaking.splice(index, 1);
			}, 2000),
		});
		if (payload.voice) {
			console.log(payload.voice);
			const voice = new Audio(STATIC_URL + payload.voice);
			voice.play();
		}
	}
};
